/**
 * @description 获取选中组件的属性和事件
 * @returns {events,currentElement,componentConfig}
 * events: 组件事件
 * currentElement: 当前选中组件
 * componentConfig: 组件配置
 */
import { useMemo } from "react";
import useComponentStore, { findComponentById } from "../store";
import useComponentConfigStore from "../store/componentConfig";

type Props = {
  id?: number; // 组件id
};

export const useCurrentComponent = (props?: Props) => {
  const { id } = props || {};
  const { componentConfig } = useComponentConfigStore();
  const {
    components,
    currentElement, // 当前选中的组件
    pageJs,
    currentId, // 当前选中的组件id
    addPageJs,
    setBindEvents,
    setCurComponentProps,
  } = useComponentStore();

  const curComponet = useMemo(() => {
    let curId = 0;
    if (id) {
      curId = id;
    } else if (currentId) {
      curId = currentId;
    }
    const curComponent = findComponentById(curId, components);
    return curComponent;
  }, [id, components]);

  const arr = componentConfig[currentElement?.name!]?.events;
  const events: Array<any> = [];
  if (arr) {
    Object.entries(arr).forEach(([key, value]) => {
      events.push(value);
    });
  }

  return {
    components,
    events,
    pageJs,
    addPageJs,
    setBindEvents,
    currentId,
    currentElement,
    componentConfig,
    curComponet, // 当前组件
    setCurComponentProps,
  };
};
